#!/usr/bin/env python3
#coding=utf-8

import os
import time

ROOT_PATH = './downImg/'
class ImgDiskManager():
    def __init__(self):
        self.refresh()

    def _getDirList(self):
        fileList = os.listdir(ROOT_PATH)
        dirList = []
        for p in fileList:
            if os.path.isdir(ROOT_PATH + p):
                dirList.append(ROOT_PATH + p + '/')
        return dirList

    def refresh(self):
        self.FileList = {}
        dirList = self._getDirList()
        dirList.sort()
        for p in dirList:
            self.FileList.update({p: os.listdir(p)})

    def fileExists(self, filename):
        for k, l in self.FileList.items():
            try:
                l.index(filename)
                return True
            except:
                pass
        return False

    def getCanSaveDirPath(self):
        for k, l in self.FileList.items():
            if len(l) < 16000:
                return k
        for i in range(99):
            if not os.path.exists(ROOT_PATH + str(i)):
                os.mkdir(ROOT_PATH + str(i))
                self.FileList.update({ROOT_PATH + str(i) + '/': []})
                return ROOT_PATH + str(i) + '/'

    def getCanSaveFilePath(self, filename):
        if not self.fileExists(filename):
            uri = self.getCanSaveDirPath()
            self.FileList[uri].append(filename)
            return uri + filename
        return False
        # return getFilePath(filename)

    def getFilePath(self, filename):
        for k, l in self.FileList.items():
            try:
                l.index(filename)
                return k + filename
            except:
                pass
        return False

    def getFileSize(self, filename):
        path = self.getFilePath(filename)
        if path:
            return os.path.getsize(path)
        return False